﻿using Grow.Module;
using Grow.Module.Builder;
using Grow.Module.Service;
using Grow.ObjectMapper.CreateObjectMapper;
using Grow.ObjectMapper.Mapster.CreateObjectMapper;
using Mapster;
using MapsterMapper;
using Microsoft.Extensions.DependencyInjection;

namespace Grow.ObjectMapper.Mapster
{
    public abstract class ObjectMapperMapsterModuleBase : ModuleBase, IObjectMapperModule
    {
        public override ModuleLevel Level => ModuleLevel.Framework;

        public override void AddDependModule(IDependModuleBuilder dependModuleBuilder)
        {
        }

        public override void AddService(IServiceContainer serviceContainer)
        {
            CreateObjectMapperBuilder createObjectMapperBuilder = new();
            CreateObjectMapper(createObjectMapperBuilder);
            serviceContainer.BuilderManager.SetBuilder<ICreateObjectMapperBuilder>(createObjectMapperBuilder);

            _ = serviceContainer.ServiceCollection.AddSingleton(new TypeAdapterConfig());
            _ = serviceContainer.ServiceCollection.AddTransient<IMapper, ServiceMapper>();
        }

        public abstract void CreateObjectMapper(ICreateObjectMapperBuilder createObjectMapperBuilder);

        public override void UseService(IServiceContext serviceContext)
        {
            TypeAdapterConfig typeAdapterConfig = serviceContext.GetRequiredService<TypeAdapterConfig>();
            //使用构造函数
            _ = typeAdapterConfig.Default.MapToConstructor(true);
            //忽略字段名称的大小写
            _ = typeAdapterConfig.Default.NameMatchingStrategy(NameMatchingStrategy.IgnoreCase);
            IBuilderManager builderManager = serviceContext.GetRequiredService<IBuilderManager>();
            ICreateObjectMapperBuilder createObjectMapperBuilder = builderManager.GetRequiredBuilder<ICreateObjectMapperBuilder>();

            IEnumerable<IObjectMapperMap> objectMapperMaps = createObjectMapperBuilder.GetObjectMapperMaps();
            ObjectMapperBuilder objectMapperBuilder = new(typeAdapterConfig);
            foreach (IObjectMapperMap objectMapperMap in objectMapperMaps)
            {
                objectMapperMap.AddObjectMapper(objectMapperBuilder);
            }
        }
    }
}